//
//  YFJourneyTagView.m
//  project
//
//  Created by Winny Zhang on 2019/3/23.
//  Copyright © 2019 健健. All rights reserved.
//

#import "YFJourneyTagView.h"


@implementation YFJourneyTagView

- (instancetype)initWithFrame:(CGRect)frame tags:(NSArray<NSString *> *)tags sameColor:(UIColor *)color {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupTags:tags sameColor:color];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame tags:(NSArray<NSString *> *)tags colors:(NSArray<UIColor *> *)colors {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupTags:tags colors:colors];
    }
    return self;
}

- (void)setupTags:(NSArray<NSString *> *)tags colors:(NSArray<UIColor *> *)colors {
    if (tags <= 0) return;
    CGFloat tagPadding = 6, tagMargin = 5;
    CGFloat tagViewWidth = self.frame.size.width;
    CGFloat allTagsWidth = 0;
    CGFloat recordTagsWidth = 0;
    for (int i = 0; i < tags.count; i++) {
        NSString *tag = tags[i];
        CGSize tagSize = [tag sizeWithFont:[UIFont boldSystemFontOfSize:11] boundingSize:CGSizeMake(MAXFLOAT, self.frame.size.height)];
        CGFloat tagW = tagSize.width + tagPadding * 2;
        
        allTagsWidth += i > 1 ? tagW + (tagMargin * (i - 1)) : tagW;
        if (allTagsWidth > tagViewWidth) { return; }

        CGFloat tagH = self.frame.size.height;
        CGFloat tagY = 0;
        CGFloat tagX = recordTagsWidth;
        UILabel *tagLabel = [[UILabel alloc] initWithFrame:CGRectMake(tagX, tagY, tagW, tagH)];
        tagLabel.textAlignment = NSTextAlignmentCenter;
        tagLabel.text = tag;
        tagLabel.font = [UIFont boldSystemFontOfSize:11];
        tagLabel.backgroundColor = [UIColor orangeColor];
        tagLabel.textColor = [UIColor whiteColor];
        tagLabel.backgroundColor = colors[i];
        [tagLabel rounded:(UIRectCornerAllCorners) radius:tagH * 0.5];
        [self addSubview:tagLabel];
        recordTagsWidth = CGRectGetMaxX(tagLabel.frame) + tagMargin;
    }
}

- (void)setupTags:(NSArray<NSString *> *)tags sameColor:(UIColor *)color {
    NSMutableArray<UIColor *> *colors = [NSMutableArray arrayWithCapacity:tags.count];
    for (int i = 0; i < tags.count; i++) {
        [colors addObject:color.copy];
    }
    [self setupTags:tags colors:colors];
}

@end
